# encoding=utf-8
import json
import logging

from django.db import models

from comm.util import jsonp, req_handler, htmlunescape


logger = logging.getLogger('apps')

    
class QQCategory(models.Model):
    id = models.BigIntegerField(primary_key=True)
    name = models.CharField(max_length=36)
    g_name = models.CharField(max_length=36)
    exts = models.CharField(max_length=512)
    
    category_item_json_url = 'http://s.plcloud.music.qq.com/fcgi-bin/fcg_get_diss_by_tag.fcg?categoryId={cid}&sortId={sid}&sin={sin}&ein={ein}&format=jsonp&g_tk=938407465&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'
    
    item_songs_json_url = 'http://qzone-music.qq.com/fcg-bin/fcg_ucc_getcdinfo_byids.fcg?type=1&json=1&utf8=1&onlysong=0&jsonpCallback=jsonCallback&nosign=1&disstid={itemid}&g_tk=938407465&loginUin=0&hostUin=0&format=jsonp&inCharset=GB2312&outCharset=utf-8&notice=0&platform=yqq&jsonpCallback=MusicJsonCallback&needNewCode=0'    
    
    def items(self):
        sorts = json.loads(self.exts)
        
        header = {'Accept':'*/*', 'Accept-Encoding':'gzip,deflate,sdch', 'Accept-Language':'en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4', 'Connection':'keep-alive',
                  'Cookie':'PATH=/; piao_city=221; qz_gdt=rhkimuydaaadk275wcca; RK=wGOq0x7EYA; qqmusic_uin=12345678; qqmusic_key=12345678; qqmusic_fromtag=30; rv2=8028E1C4053F2EEEC256531624E6444B948A92C204A19385EB; property20=C595E819D5B6A0FDE0506F13FD90A4B532FC3B7D2776EEE01799448DE7A1B0325F69FC5F22149621; verifysession=h02iFs3e8tEjTM2yTdyyVy9UiQp-asUvgDJSg-Pxc9wKmGqJjq_ihnCHur_EEQPf4_Gr2rvs0ViTGr0xRbsNf-Hvw**; qm_authimgs_id=0; qm_verifyimagesession=h01653b47a1caa271d1b215c9cd53bcb45b39975a0922bd68b2832d7dae5d6adb5f71b0e9fa7b8a9891; pgv_info=ssid=s7232259648; pgv_pvid=9643858795; o_cookie=314491185; dm_login_weixin_scan=; isVideo_DC=0; ptui_loginuin=1509788891@qq.com; ptisp=ctc; ptcz=02af862c4ab92e892204c898c7c638b442f8d57566f4ada85c10a68000331a40; pt2gguin=o0314491185; qm_sid=5df4449c567eedb1b21c5a1781c52904,ctEdbaIAOVv4.; qm_username=2617855264; qm_sk=-1677112032&RQfTj-MZ|-1680469063&RQfTj-MZ; qm_ssum=-1677112032&d49abfed99cf1690997c8be449328c74|-1680469063&d97b439925025b6dfb822fa08a603eec',
                  'Host':'s.plcloud.music.qq.com',
                  'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
                  'Referer':'http://y.qq.com/y/static/taoge/taoge_list.html?pgv_ref=qqmusic.y.topmenu'}

        for sort in sorts:
            sin = 0
            ein = 19
            err_num = 0
            csum = 0
            while True:
                sort_id = sort['sortId']
                url = QQCategory.category_item_json_url.format(cid=self.id, sid=sort_id, sin=sin, ein=ein)
                rsp_html = req_handler(url, header)
                logger.info("item rsp" + rsp_html)
                json_obj = jsonp(rsp_html)
                code = json_obj['code']
                if code == 0:
                    data = json_obj['data']
                    items = data['list']
                    for item in items:
                        itemid = item['dissid']
                        entity = QQCategoryItem()
                        entity.parse(item)
                        entity.pid = self.id
                        entity.sort_id = sort_id
                        
                        url = QQCategory.item_songs_json_url.format(itemid=itemid)
                        rsp_html = req_handler(url, header)
                        logger.info("itemdetail : " + rsp_html)
                        rsp_html = htmlunescape(rsp_html)
                        json_obj = jsonp(rsp_html)
                        code = json_obj['code']
                        if code == 0:
                            cdlist = json_obj['cdlist']
                            for cditem in cdlist:
                                entity.tags = json.dumps(cditem['tags'])
                                entity.song_ids = cditem['songids']
                                entity.song_num = cditem['songnum']
                                entity.song_types = cditem['songtypes']
                                songlist = cditem['songlist']
                                
                                for song in songlist:
                                    sentity = QQItemSong()
                                    sentity.parse(song)
                                    sentity.pid = itemid
                                    sentity.save()
                                    
                        entity.exts['detail'] = rsp_html
                        entity.save()
                        
                    csum = data['sum']
                    if ein >= csum or err_num >= 3:
                        break
                    elif err_num > 0:
                        err_num = err_num - 1
                else:
                    err_num = err_num + 1
                sin = ein + 1
                ein = sin + 19
            
    def __unicode__(self):
        return "%s %s %s %s" % (self.id, self.name, self.g_name, self.exts);
    
    class Meta:
        db_table = 'tb_qq_category'
        ordering = ['id']
        verbose_name = u'QQItem'
        verbose_name_plural = u'QQCategory'
        
        
class QQCategoryItem(models.Model):
    id = models.BigIntegerField(primary_key=True)
    name = models.CharField(max_length=128)
    imgurl = models.CharField(max_length=128)
    descro = models.CharField(max_length=512)
    pid = models.BigIntegerField()
    sort_id = models.IntegerField()
    listen = models.IntegerField()
    song_num = models.IntegerField()
    song_ids = models.CharField(max_length=512)
    song_types = models.CharField(max_length=256)
    tags = models.CharField(max_length=512)
    ctime = models.CharField(max_length=36)
    
    exts = models.TextField()
    
    status = models.CharField(max_length=36)
    
    class Meta:
        db_table = 'tb_qq_category_item'
    
    def parse(self, jsobj):
        self.id = jsobj['dissid']
        self.name = jsobj['dissname']
        self.imgurl = jsobj['imgurl']
        self.descro = jsobj['introduction']
        self.listen = jsobj['listennum']
        self.score = jsobj['score']
        exts = {}
        exts['creator'] = json.dumps(jsobj['creator'])
        exts['version'] = jsobj['version']
        exts['rsp'] = json.dumps(jsobj)
        self.exts = exts
        
    

class QQItemSong(models.Model):
    id = models.BigIntegerField(primary_key=True)
    type = models.IntegerField()
    name = models.CharField(max_length=128)
    url = models.CharField(max_length=128)
    descro = models.CharField(max_length=512)
    
    singer_name = models.CharField(max_length=128)
    singer_id = models.BigIntegerField()
    album_name = models.CharField(max_length=128)
    album_id = models.BigIntegerField()
    
    pid = models.BigIntegerField()

    status = models.CharField(max_length=36)
    
    exts = models.TextField()
    
    class Meta:
        db_table = 'tb_qq_category_item_song'
    
    def parse(self, jsobj):
        self.id = jsobj['songid']
        self.type = jsobj['songtype']
        self.name = htmlunescape(jsobj['songname'])
        self.url = htmlunescape(jsobj['url'])
        self.singer_name = htmlunescape(jsobj['singername'])
        self.singer_id = jsobj['singerid']
        self.album_name = htmlunescape(jsobj['diskname'])
        self.album_id = jsobj['diskid']
        exts = {}
        exts['rsp'] = htmlunescape(json.dumps(jsobj))
        self.exts = exts
        
    
        
